<?php

namespace app\admin\controller\courseevent;

use app\common\controller\Backend;
use fast\Tree;
/**
 * 
 *
 * @icon fa fa-file
 */
class Courseevent extends Backend
{
    
    /**
     * Courseevent模型对象
     */
    protected $model = null;
    protected $noNeedRight=["lists","status"];
    protected $noNeedLogin=["lists","status"];



    public function _initialize()
    {
        parent::_initialize();
        $this->shopid=false;
        $this->model = model('Courseevent');
        $this->modelValidate = true;
    }
    
    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */

    /**
     * 查看
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags']);

        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $total = $this->model
                ->where($where);
            if(isset($_REQUEST["type"])&&$_REQUEST["type"]=="recyclebin"){
                $total = $total->where("status", "=", -1);
            }else{
                $total = $total->where("status", "<>", -1);
            }

            //if ($_SESSION['think']['admin']['group_id'] == 2) {
            //    $total = $total->where("city_id", "=", $_SESSION['think']['admin']['city_id']);
            //}
            $total = $total->count();

            $list = $this->model
                ->where($where);
            //if ($_SESSION['think']['admin']['group_id'] == 2) {
            //    $list = $list->where("city_id", "=", $_SESSION['think']['admin']['city_id']);
            //}
            if(isset($_REQUEST["type"])&&$_REQUEST["type"]=="recyclebin"){
                $list = $list->where("status", "=", -1);
            }else{
                $list = $list->where("status", "<>", -1);
            }
            $list = $list
                //->order('weigh desc,id desc')
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();
            //$this->model->getLastSql();
            $list = collection($list)->toArray();

//            $tree = Tree::instance();
//            $tree->init($list, 'pid');
//            $list = $tree->getTreeList($tree->getTreeArray(0), 'name');
//            $data = array();
//            for ($i = 0; $i < count($list); $i++) {
//                $v = $list[$i];
//                $data[] = [
//                    'id' => $v['id'],
//                    'parent' => $v['pid'] ? $v['pid'] : '#',
//                    'name' => $v['name'],
//                    'type' => $v['type'],
//                    'status' => $v['status'],
//                    'school_id' => model("School")->getSchool_idTextAttr($v['school_id'])
//                ];
//            }


            for($i=0;$i<count($list);$i++){
//                $list[$i]['province_id']=model('Cityarea')->getProvince_idTextAttr($list[$i]['province_id']);
//                $list[$i]['city_id']=model('Cityarea')->getCity_idTextAttr($list[$i]['city_id']);
//                $list[$i]['district_id']=model('Cityarea')->getDistrict_idTextAttr($list[$i]['district_id']);
//                $list[$i]['province_id']=preg_replace("/\/$/","",model('Cityarea')->getProvince_idTextAttr($list[$i]['province_id'])."/".$list[$i]['city_id']."/".$list[$i]['district_id']);
                $list[$i]['subjectlv_id']=model('Subjectlv')->getSubjectlv_idTextAttr($list[$i]['subjectlv_id'],$list[$i]);
                $list[$i]['course_id']=model('Course')->getCourse_idTextAttr($list[$i]['course_id'],$list[$i]);
                $list[$i]['ocation_id']=model("Ocation")->getOcation_idTextAttr($list[$i]['ocation_id'],$list[$i]);
                $list[$i]['classes_id']=model("Classes")->getClasses_idTextAttr($list[$i]['classes_id'],$list[$i]);
            }
            $result = array("total" => $total, "rows" => $list);
            return json($result);
        }
//        $this->assignconfig("relType",$_REQUEST['relType']);
//        $this->assignconfig("relId",$_REQUEST['relId']);
        $this->assignconfig("admin",$_SESSION['think']['admin']);
        return $this->view->fetch();
    }
    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                    $params[$this->dataLimitField] = $this->auth->id;
                }
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                        $this->model->validate($validate);
                    }
                    $datatime=date("Y-m-d H:i:s");
                    $params['create_time']=$datatime;
                    unset($params['delete_time']);
                    unset($params['update_time']);
//                    if($_SESSION['think']['admin']['group_id']==2){
//                        $params['city_id']=$_SESSION['think']['admin']['city_id'];
//                    }
                    $result = $this->model->allowField(true)->save($params);
                    if ($result !== false) {
                        $this->success();
                    } else {
                        $this->error($this->model->getError());
                    }
                } catch (\think\exception\PDOException $e) {
                    $this->error($e->getMessage());
                } catch (\think\Exception $e) {
                    $this->error($e->getMessage());
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $this->assignconfig("admin",$_SESSION['think']['admin']);
        $event_time=time();
        $this->view->assign("event_time", $event_time);
        return $this->view->fetch();
    }

    /**
     * 编辑
     */
    public function edit($ids = NULL)
    {
        $row = $this->model->get($ids);
        if (!$row)
            $this->error(__('No Results were found'));
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                        $row->validate($validate);
                    }
                    $datatime=date("Y-m-d H:i:s");
                    $params['update_time']=$datatime;
                    unset($params['delete_time']);
                    unset($params['create_time']);
//                    if($_SESSION['think']['admin']['group_id']==2){
//                        $params['city_id']=$_SESSION['think']['admin']['city_id'];
//                    }
                    $result = $row->allowField(true)->save($params);
                    if ($result !== false) {
                        $this->success();
                    } else {
                        $this->error($row->getError());
                    }
                } catch (\think\exception\PDOException $e) {
                    $this->error($e->getMessage());
                } catch (\think\Exception $e) {
                    $this->error($e->getMessage());
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $this->assignconfig("admin",$_SESSION['think']['admin']);
        $this->view->assign("row", $row);
        return $this->view->fetch();

    }

    /**
     * 添加
     */
    public function view($ids = NULL)
    {
        $row=$this->model->getRow($ids);
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }


    public function restore($ids = null)
    {
        if ($ids) {
            $count = $this->model->onlyTrashed()->where('id', 'in', $ids)->update(['deletemark' => 0]);
            if ($count) {
                $this->success('恢复成功');
            } else {
                $this->error('恢复失败');
            }
        } else {
            $this->error(__('Parameter %s can not be empty', 'ids'));
        }
    }

    public function force($ids = null)
    {
        if ($ids) {
            $count = $this->model->onlyTrashed()->where('id', 'in', $ids)->delete(true);
            if ($count) {
                $this->success('彻底删除成功');
            } else {
                $this->error('彻底删除失败');
            }
        } else {
            $this->error(__('Parameter %s can not be empty', 'ids'));
        }
    }

    public function lists($ids = NULL){
        $where="where 1=1";
        if($_SESSION['think']['admin']['group_id']!=1){
            $where.=" and city_id='{$_SESSION['think']['admin']['city_id']}'";
        }
        $page=1;
        $pagesize=50;
        if ($this->request->isAjax()) {
            if ($this->request->request('keyField')) {
                $keyField = $this->request->request("keyField");
                $keyValue = $this->request->request("keyValue");
                $page = $this->request->request("pageNumber");
                $page = ($page == null) ? 1 : $page;
                $pagesize = $this->request->request("pageSize");
                $pagesize = ($pagesize == null) ? 10 : $pagesize;
                if ($keyValue != "") {
                    $nn=preg_split("/\,/",$keyValue);
                    for($i=0;$i<count($nn);$i++) {
                        $where.= " and $keyField='{$nn[$i]}'";
                    }
                }
            }else{
                $where="where 1=1";
                if(isset($_REQUEST['city_id'])&&$_REQUEST['city_id']>0){
                    //$where.=" and city_id=".$_REQUEST['city_id'];
                }
            }
        }
        $sql="select id,__firstfield__ name from dev002_gxyusheng.course_external_event $where limit " . (($page - 1) * $pagesize) . ",$pagesize";
        $list = db()->query($sql);

//        $r_name = model("School")->field("id,name")->where("id", "=", $_REQUEST['school_id'])->select();
//        if (empty($list)&&!empty($r_name)) {
//            $data = array(
//                "type" => "file",
//                "pid" => 0,
//                "name" => $r_name[0]['name']."学科",
//                "title" => $r_name[0]['name'],
//                "ismenu" => 0,
//                "createtime" => time(),
//                "updatetime" => time(),
//                "status" => 1,
//                "school_id" => $_REQUEST['school_id'],
//            );
//            $this->model->create($data);
//        }
//        $sql="select id,pid,name,title,status from dev002_gxyusheng.course_external_event $where limit " . (($page - 1) * $pagesize) . ",$pagesize";
//        $list = db()->query($sql);
//        $tree = Tree::instance();
//        $tree->init($list, 'pid');
//        $list = $tree->getTreeList($tree->getTreeArray(0), 'name');

        $total = db()->query("select count(1) as c from  dev002_gxyusheng.course_external_event $where")[0];
        echo json_encode(array("list" => $list, "total" => $total['c']));
        exit;
    }

    public function status($ids = '')
    {
        $ids = $this->request->post('ids');
        if (empty($ids)) {
            $this->error('没有选中!');
        }
        try {
            $result=$this->model->where("id","=",$ids)->field("status")->find();
            $v=$result->status==1?0:1;
            $this->model->where("id","=",$ids)->update(["status"=>$v]);
            $this->success('切换成功!');
        } catch (Exception $e) {
            $this->error('切换失败!'.$e->getMessage());
        }
    }

    public function changeStatus($ids = '')
    {
        $ids = $this->request->post('ids');
        if (empty($ids)) {
            $this->error('没有选中!');
        }
        try {
            $result=$this->model->where("id","=",$ids)->field("status")->find();
            $v=$result->status==1?0:1;
            $this->model->where("id","=",$ids)->update(["status"=>$v]);
            $this->success('切换成功!');
        } catch (Exception $e) {
            $this->error('切换失败!'.$e->getMessage());
        }
    }

}
